﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using ZBJF.Warranty.Common.Common;

namespace ZBJF.Warranty.WebProvider
{
    public class WebApiCaller
    {
        public WebApiCaller()
        {
            ApiEncoding = Encoding.UTF8;
            Method = "POST";
        }

        public WebApiCaller(Encoding apiEncoding)
        {
            ApiEncoding = apiEncoding;
        }

        private Encoding ApiEncoding { get; set; }
        private string Method { get; set; }


        public string Get(string url, string jsonData)
        {
            Method = "GET";
            return GetDataFormUrl(url, jsonData);
        }

        public string Post(string url, string jsonData)
        {
            Method = "POST";
            return GetDataFormUrl(url, jsonData);
        }

        private string GetDataFormUrl(string url, string jsonData)
        {
            string retString;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = Method;

                request.Accept = "application/json";
                request.ContentType = "application/json";

                request.ContentLength = Encoding.UTF8.GetBytes(jsonData).Length;

                //这个在Post的时候，一定要加上，如果服务器返回错误，他还会继续再去请求，不会使用之前的错误数据，做返回数据
                request.ServicePoint.Expect100Continue = false;

                Stream myRequestStream = null;
                try
                {
                    myRequestStream = request.GetRequestStream();
                    myRequestStream.Write(Encoding.UTF8.GetBytes(jsonData), 0, Encoding.UTF8.GetBytes(jsonData).Length);
                }
                catch (Exception ex)
                {

                }
                finally
                {
                    if (myRequestStream != null)
                    {
                        myRequestStream.Close();
                        myRequestStream.Dispose();
                    }
                }


                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    var responseStream = response.GetResponseStream();
                    if (responseStream != null)
                    {
                        using (StreamReader myStreamReader = new StreamReader(responseStream,
                            ApiEncoding))
                        {
                            retString = myStreamReader.ReadToEnd();
                        }
                    }
                    else
                    {
                        retString = "has no data response!";
                    }
                }

            }
            catch (Exception ex)
            {
                retString = ex.ToString();
            }

            return retString;
        }
    }

}
